package xamap

import (
	"fmt"
	"strings"

	"github.com/tealeg/xlsx"
)

var sheet *xlsx.Sheet

// 从xls中进行读取城市名称
//
//	city_code	城市代码
func getCityCode(city_code string) (string, error) {
	if sheet == nil {
		xlsx, err := xlsx.OpenBinary(citycode)
		if err != nil {
			return "", err
		}
		// 打开sheet0
		sheet = xlsx.Sheets[0]
	}
	for i, row := range sheet.Rows {
		if i == 0 {
			continue
		}
		if row.Cells[1].Value == city_code {
			return row.Cells[0].Value, nil
		}
	}
	return "", nil
}

// 获取城市名称
//
//	city_code	城市代码
func GetCityName(city_code uint) string {
	// code转字符串
	city_code_str := fmt.Sprintf("%d", city_code)
	if len(city_code_str) != 6 {
		city_code_str = city_code_str + "000000"
	}
	city_code_str = city_code_str[:6]
	// 省名称
	province_name, err := getCityCode(city_code_str[:2] + "0000")
	if err != nil {
		return ""
	}
	// 市区名称
	city_name, err := getCityCode(city_code_str[:4] + "00")
	if err != nil {
		return ""
	}
	// 区名称
	district_name, err := getCityCode(city_code_str)
	if err != nil {
		return ""
	}
	slices := []string{}
	if province_name != "" {
		slices = append(slices, province_name)
	}
	if city_name != "" {
		slices = append(slices, city_name)
	}
	if district_name != "" {
		slices = append(slices, district_name)
	}
	return strings.Join(slices, "/")
}
